﻿using CqBuiltinService.Extensions;
using CqCore.Logging;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace CqBuiltinService.Requests
{
    public class RequestedTrackFilter : IAsyncResultFilter, IAsyncExceptionFilter
    {
        readonly ILogRecorder logger;

        public RequestedTrackFilter(ILogRecorder<RequestedTrackFilter> logger)
        {
            this.logger = logger;
        }

        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            await next();

            logger.Info(new EventData
            {
                Type = $"{context.ActionDescriptor.DisplayName}",
                Message = "Completed",
                Labels = {
                    ["TraceId"] = context.HttpContext.TraceIdentifier,
                    ["Method"] = context.HttpContext.Request.Method,
                    ["Path"] = context.HttpContext.Request.Path.Value,
                    ["Query"] = context.HttpContext.Request.QueryString.Value,
                    ["Arguments"] = JsonConvert.SerializeObject(context.ModelState.ToDataDictionary()),
                    ["StatusCode"] = $"{context.HttpContext.Response.StatusCode}"
                }
            });
        }

        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.Error(new EventData
            {
                Type = $"{context.ActionDescriptor.DisplayName}",
                Message = context.Exception.GetBaseException().Message,
                Labels = {
                    ["TraceId"] = context.HttpContext.TraceIdentifier,
                    ["Method"] = context.HttpContext.Request.Method,
                    ["Path"] = context.HttpContext.Request.Path.Value,
                    ["Query"] = context.HttpContext.Request.QueryString.Value,
                    ["Arguments"] = JsonConvert.SerializeObject(context.ModelState.ToDataDictionary()),
                    ["StatusCode"] = $"{500}"
                }
            });
        }
    }
}
